package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.WxPayVo;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.util.WeChatPayUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 支付方式
 * Created by Administrator on 2016/11/24.
 */
public class ReadyPayActivity extends BaseActivity implements View.OnClickListener {
    //数据库
    private DBManager db = null;
    //加载框
    AlertDialog dialog;
    //标记是哪种支付
    public static String sign;
    //类对象
    public static ReadyPayActivity readyPayActivity = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_readypay);
        db = new DBManager(this);
        readyPayActivity = this;
        //EventBus的注册
//        EventBus.getDefault().register(this);
        TextView name = (TextView) findViewById(R.id.activity_readypay_companyName);
        TextView type = (TextView) findViewById(R.id.activity_readypay_serviceType);
        TextView count = (TextView) findViewById(R.id.activity_readypay_serviceCount);
        TextView cost = (TextView) findViewById(R.id.activity_readypay_price);
        TextView pay_tv = (TextView) findViewById(R.id.activity_readypay_pay);
        ImageView img_back = (ImageView) findViewById(R.id.img_back);
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_readypay_rl);
        RelativeLayout rl_02 = (RelativeLayout) findViewById(R.id.activity_readypay_rl02);
        TextView name_02 = (TextView) findViewById(R.id.activity_readypay_companyName02);
        TextView type_02 = (TextView) findViewById(R.id.activity_readypay_serviceType02);
        TextView time_02 = (TextView) findViewById(R.id.activity_readypay_servicetime02);
        TextView cost_02 = (TextView) findViewById(R.id.activity_readypay_price02);
        TextView pay_tv02 = (TextView) findViewById(R.id.activity_readypay_pay02);
        TextView title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("服务内容");
        pay_tv.setOnClickListener(this);
        pay_tv02.setOnClickListener(this);
        img_back.setOnClickListener(this);
        if (getIntent().getStringExtra("sign").equals("MonitorSelectActivity")) {
            String name1 = getIntent().getStringExtra("name");
            String companyName = getIntent().getStringExtra("companyName");
            String serviceType = getIntent().getStringExtra("serviceType");
            String serviceCount = getIntent().getStringExtra("serviceCount");
            String description = getIntent().getStringExtra("description");
            String price = getIntent().getStringExtra("price");
            rl.setVisibility(View.VISIBLE);
            rl_02.setVisibility(View.GONE);
            name.setText("医院: " + companyName);
            if (description != null && !description.equals("") && !description.equals("null")) {
                type.setText("服务类型: " + name1);
                count.setText(Html.fromHtml(description));
            }else{
                type.setText("服务类型: " + serviceType);
                count.setText("服务次数: " + serviceCount + "次");
            }
            if(cost.getVisibility()==View.VISIBLE){
                cost.setVisibility(View.GONE);
            }
            cost.setText("费用: " + price + "元");

        } else if (getIntent().getStringExtra("sign").equals("VIPActivity")) {
            rl.setVisibility(View.GONE);
            rl_02.setVisibility(View.VISIBLE);
            name_02.setText("服务名称：" + getIntent().getStringExtra("name_02"));
            type_02.setText("服务类型: " + getIntent().getStringExtra("type_02"));
            time_02.setText("购买时长：" + getIntent().getStringExtra("count_02") + "个月");
            cost_02.setText("费用: " + getIntent().getStringExtra("price_02") + "元");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_readypay_pay:
                sign = "";
                dialog = new MyAlertDialog().ShowDialog(ReadyPayActivity.this, R.layout.dialog_loading);
                getData();
                break;
            case R.id.activity_readypay_pay02:
                sign = "vip";
                dialog = new MyAlertDialog().ShowDialog(ReadyPayActivity.this, R.layout.dialog_loading);
                getData();
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }

    public void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, Object> param = new HashMap<>();
                    if (getIntent().getStringExtra("sign").equals("MonitorSelectActivity")) {
                        param.put("serviceProductId", Integer.parseInt(getIntent().getStringExtra("id")));
                        param.put("productCount", 1);
                        param.put("payMethod", "WechatAppPay");
                    } else if (getIntent().getStringExtra("sign").equals("VIPActivity")) {
                        param.put("serviceProductId", Integer.parseInt(getIntent().getStringExtra("id_02")));
                        param.put("productCount", 1);
                        param.put("payMethod", "WechatAppPay");
                    }
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.WXPay).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }


        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    if (isWeixinAvilible(ReadyPayActivity.this)) {
                        onJsonData(msg.obj.toString());
                        ToastUtil.showToast(ReadyPayActivity.this, "正在打开微信支付...");
                    } else {
                        ToastUtil.showToast(ReadyPayActivity.this, "您还没有安装微信，请先安装微信客户端");
                    }
                    break;
                case 1:
                    ToastUtil.showToast(ReadyPayActivity.this, "支付失败");
                    break;
                case 2:
                    ToastUtil.showToast(ReadyPayActivity.this, "支付成功");
                    break;
            }
        }
    };

    private void onJsonData(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            String prepayid = jsonObject.optString("prepayid");
            String noncestr = jsonObject.optString("noncestr");
            String timestamp = jsonObject.optString("timestamp");
            String sign = jsonObject.optString("sign");
            WxPayVo wxPayVo = new WxPayVo(timestamp, sign, noncestr, prepayid);
            new WeChatPayUtils(ReadyPayActivity.this).pay(wxPayVo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
